package com.zhan.rkforum.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author wujiazhan
 * @className MailClient
 * @description 邮件工具类
 * @date 2021-05-27 12:08
 */
@Component
public class MailUtil {
    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String form;

    public void sendMail(String to, String subject, String context) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);//使用massageHelp设置邮件信息
            helper.setFrom(form);
            helper.setTo(to);//设置目标邮箱
            helper.setSubject(subject);//设置主题
            helper.setText(context, true);//第一个参数：设置内容，第二个参数：是否支将内容渲染为html
            mailSender.send(helper.getMimeMessage());//发送邮件
        } catch (MessagingException e) {
            logger.error("右键发送错误信息：", e.getMessage());
        }
    }

}
